package com.hourse.controller;

import com.hourse.pojo.TbUser;
import com.hourse.service.UserService;
import com.hourse.util.JwtUtil;
import com.hourse.util.Result;
import com.hourse.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping
    public List<TbUser> list(){
        return userService.userList();
    }
    @GetMapping("/{id}")
    public Result findById(@PathVariable Long id){
      TbUser user= userService.findById(id);
        return new Result(true, StatusCode.OK,"查询成功",user);
    }
    /*
    * 发送短信*/
    @RequestMapping(value = "/yzm/{mobile}",method = RequestMethod.POST)
    public Result sendSms(@PathVariable String mobile){
        userService.sendSms(mobile);
        return new Result(true,StatusCode.OK,"发送成功");
    }
//    从redis获取验证码
    @RequestMapping(value = "/getyzm/{mobile}",method = RequestMethod.GET)
    public Result huqvYzm(@PathVariable String mobile){
        Object s=userService.huoqvYzn(mobile);
        return new Result(true,StatusCode.OK,"获取成功",s);
    }
    /*
    * 注册*/
    @RequestMapping(value = "/register/{code}",method = RequestMethod.POST)
    public Result regist(@PathVariable String code,@RequestBody TbUser user){
        String checkcodeRedis = (String) redisTemplate.opsForValue().get("yzm"+user.getPhone());
        if (checkcodeRedis==null){
            return new Result(false,StatusCode.ERROR,"请先获取验证码");
        }
        if (!checkcodeRedis.equals(code)){
            return new Result(false,StatusCode.ERROR,"验证码错误");
        }

        userService.add(user);
        return new Result(true,StatusCode.OK,"注册成功");


    }
    /*
    * 登录*/
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody TbUser tbUser){
       TbUser user=userService.login(tbUser.getPhone(),tbUser.getPassword());
        if (user==null){
            return new Result(false,StatusCode.LOGINERROR,"登录失败");
        }
        //使得前后端可以通话的操作。采用JwT来实现
        //生成令牌
        String token = jwtUtil.createJWT(user.getId() + "", user.getNickname(), "admin");
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("role","user");
        return new Result(true,StatusCode.OK,"登录成功",map);
    }
    /*
    * 删除 必须有admin角色才能删除*/
    @RequestMapping(value="/{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable Long id){
        userService.deleteById(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }
}
